/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PatientSchedule.java
 *
 * Created on Aug 26, 2011, 10:43:36 PM
 */
package patientManager;

import app.Global;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Fun
 */
public class PatientSchedule extends java.awt.Dialog {

    Vector vData;
    Vector vColumn;
    
    private static class Department {

        int id;
        String name;

        public Department(int aInt, String string) {
            this.id = aInt;
            this.name = string;
        }

        @Override
        public String toString() {
            return name;
        }
    }
    String name;
    int id;
    int emp_id;
    Vector v;
    /** Creates new form PatientSchedule */
    public PatientSchedule(java.awt.Frame parent, boolean modal, String name, int id, int emp_id, int stt) {
        super(parent, modal);
        initComponents();
        txtPatientName.setText(name);
        this.id = id;
        this.emp_id = emp_id;
        System.out.println(emp_id);
        if(stt==3){
            initDepartment();
            cbbDepartment.setEnabled(true);
        } else {
//            emp_id =  Integer.parseInt(v.lastElement().toString());            
            initDepartment();
            cbbDepartment.setEnabled(false);
            initField();
        }
        this.setVisible(true);
    }
    void initField(){
        Connection cn = Global.getConnection();
        Statement st = null;
        ResultSet rs = null;

        try {st = cn.createStatement();
            rs = st.executeQuery("SELECT     departments.name, employees.first_name, employees.last_name"
                                +" FROM         departments INNER JOIN"
                                +" employees ON departments.id = employees.department_id "
                                +" where employees.id = "+ emp_id);
            while (rs.next()) {
                txtDoctor.setText(rs.getString(2)+" "+rs.getString(3));
                cbbDepartment.setSelectedItem(rs.getString(1));
            }
        } catch (SQLException ex) {
        } finally {
            try {
                rs.close();
                st.close();
                cn.close();
            } catch (SQLException ex) {
            }
        }
    }
    
    void initDepartment() {
        Connection cn = Global.getConnection();
        Statement st = null;
        ResultSet rs = null;

        try {st = cn.createStatement();
            rs = st.executeQuery("SELECT id, name FROM    departments");
            while (rs.next()) {
                cbbDepartment.addItem(new Department(rs.getInt(1), rs.getString(2)));
            }
        } catch (SQLException ex) {
        } finally {
            try {
                rs.close();
                st.close();
                cn.close();
            } catch (SQLException ex) {
            }
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtPatientName = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        cbbDepartment = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        txtDoctor = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        taDescription = new javax.swing.JTextArea();
        txtTime = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                closeDialog(evt);
            }
        });

        jPanel2.setLayout(new java.awt.BorderLayout());

        jPanel3.setPreferredSize(new java.awt.Dimension(330, 100));

        jLabel1.setText("Patient Name :");

        txtPatientName.setEditable(false);

        jLabel2.setText("Department :");

        cbbDepartment.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbbDepartmentActionPerformed(evt);
            }
        });

        jLabel3.setText("Doctor :");

        txtDoctor.setEditable(false);

        jLabel4.setText("Schedule Time :");

        jLabel6.setText("Description :");

        taDescription.setColumns(20);
        taDescription.setRows(5);
        jScrollPane1.setViewportView(taDescription);

        txtTime.setEditable(false);

        jButton1.setText("Add new patient schedule");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Cancel");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addGap(29, 29, 29)
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(cbbDepartment, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(txtDoctor, javax.swing.GroupLayout.DEFAULT_SIZE, 181, Short.MAX_VALUE)
                                    .addComponent(txtPatientName)
                                    .addComponent(txtTime, javax.swing.GroupLayout.Alignment.TRAILING)))
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE))))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(35, 35, 35)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 63, Short.MAX_VALUE)
                        .addComponent(jButton2)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtPatientName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(30, 30, 30)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cbbDepartment, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(43, 43, 43)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtDoctor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(30, 30, 30)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(36, 36, 36)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton2)
                    .addComponent(jButton1))
                .addContainerGap(31, Short.MAX_VALUE))
        );

        jPanel2.add(jPanel3, java.awt.BorderLayout.LINE_START);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(jTable1);

        jPanel4.add(jScrollPane2);

        jPanel2.add(jPanel4, java.awt.BorderLayout.CENTER);

        jPanel1.add(jPanel2);

        add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /** Closes the dialog */
    private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
        setVisible(false);
        dispose();

    }//GEN-LAST:event_closeDialog

    private void cbbDepartmentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbbDepartmentActionPerformed
        // TODO add your handling code here:
        vData = new Vector();
        vColumn = new Vector();
        Department de = (Department) cbbDepartment.getSelectedItem();
        System.out.println(de.id);
        Connection cn = Global.getConnection();
        Statement st = null;
        ResultSet rs = null;

        try {
            st = cn.createStatement();
            rs = st.executeQuery("SELECT     employees.first_name, employees.last_name, employee_schedules.date, "
                    + " employee_schedules.time_slot, employee_schedules.status, employees.id"
                    + " FROM         employee_schedules INNER JOIN"
                    + " employees ON employee_schedules.employee_id = employees.id"
                    + " where employees.department_id = "+de.id);
            ResultSetMetaData rsmt = rs.getMetaData();
            for (int i = 1; i < rsmt.getColumnCount(); i++) {
                if (i == 1) {
                    vColumn.add("DoctorName");
                    i++;
                } else {
                    vColumn.add(rsmt.getColumnName(i));
                }
            }
            while (rs.next()) {
                Vector vRow = new Vector();
                for (int i = 1; i <= rsmt.getColumnCount(); i++) {
                    if (i == 1) {
                        vRow.add(rs.getString(i) + " " + rs.getString(i + 1));
                        i++;
                    } else if (i == rsmt.getColumnCount()) {
                        emp_id = rs.getInt(i);
                    } else {
                        vRow.add(rs.getString(i));
                    }
                }
                vData.add(vRow);
            }
            jTable1.setModel(new DefaultTableModel(vData, vColumn) {

                @Override
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            });
        } catch (SQLException ex) {
            Logger.getLogger(PatientDetail.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                rs.close();
                st.close();
                cn.close();
            } catch (SQLException ex) {
                Logger.getLogger(PatientDetail.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }//GEN-LAST:event_cbbDepartmentActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        // TODO add your handling code here:
        Vector v = (Vector) vData.get(jTable1.getSelectedRow());
        String name = v.get(0).toString();
        txtDoctor.setText(name);
        txtTime.setText(v.get(1).toString());
    }//GEN-LAST:event_jTable1MouseClicked

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        // TODO add your handling code here:
        Connection cn = Global.getConnection();
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            pst = cn.prepareStatement("INSERT  patient_schedules(patient_id,employee_id,scheduled_time,note,status,created)"
                    + " values (?,?,?,?,?,?)");
            pst.setInt(1, id);
            pst.setInt(2, emp_id);
            pst.setString(3, txtTime.getText());
            pst.setString(4, taDescription.getText());
            pst.setInt(5, 1);
            Date todayD = new Date(System.currentTimeMillis());
            SimpleDateFormat dayFormat = new SimpleDateFormat("MM/dd/yyyy");
            String todayS = dayFormat.format(todayD.getTime());
            pst.setString(6, todayS);
            int i = pst.executeUpdate();
            if (i > 0) {
                JOptionPane.showMessageDialog(this, "SUCCESSFUL");
                this.dispose();
            } else {
                JOptionPane.showMessageDialog(this, "UNSUCCESSFUL");
            }
        } catch (SQLException ex) {
            Logger.getLogger(PatientSchedule.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                pst.close();
                cn.close();
            } catch (SQLException ex) {
                Logger.getLogger(PatientSchedule.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cbbDepartment;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextArea taDescription;
    private javax.swing.JTextField txtDoctor;
    private javax.swing.JTextField txtPatientName;
    private javax.swing.JTextField txtTime;
    // End of variables declaration//GEN-END:variables
}
